#!/usr/bin/python
import sys,os
import math
import operator
import math,datetime
import urllib2
import socket

class stockinfo:
	"""stock collection moudle for collecting stock information""" 
	def __init__(self,self_profile=".quote.TW",ref_profile=".mquote.TW",nosort=0,cname=0):
		self.nosort=nosort
		self.cname=cname
		self.PROFILE=ref_profile
		self.SELF_PROFILE=self_profile
		self.REF_PROFILE=ref_profile
		self.CSVURL="http://mis.tse.com.tw/data/%s.csv"
	def get_TSEIndex(self):
		socket.setdefaulttimeout(10)
		try:
		    page = urllib2.urlopen(self.CSVURL%('TSEIndex'))
		except URLError, e:
		    print e.reason
		one_page=page.read()
		return one_page.split("\n")[1].split(",")[2].replace('"','')
		"""
		#source from yahoo finance
		f = os.popen("yahooquote ^TWII")
		cur_items=f.read().rstrip().split("\t")
		cur_price=cur_items[2]
		f.close()
		return cur_price
		"""

	def get_stockinfo(self, StkNo):
		socket.setdefaulttimeout(10)
		try:
		   page = urllib2.urlopen(self.CSVURL%(StkNo))
		except URLError, e:
		   print e.reason
		   

		one_page=page.read()
		try:
     		   value =unicode(one_page, 'big5')
		except:
	  	   value = os.popen('echo "%s" |iconv -f big5 -t utf8 2>&1'%one_page).read()
		value=value.split(",")
		return (value[-1].replace('"',''),value[8].replace('"',''))
		"""
		#source from yahoo finance
		f = os.popen("yahooquote %s"%(id))
		cur_items=f.read().rstrip().split("\t")
		cur_price=float(cur_items[2])
		f.close()
		return cur_price
		"""

	def stock_monitor(self):
		f = open(os.environ['HOME']+"/"+self.PROFILE,'r')
		stocks=f.read()
		f.close()
		profit_total=0
		cost_total=0
		sale_total=0

		cur_price=self.get_TSEIndex()
		"""TSEC weighted index: """
		print "#TSEC:%s (%s)"%(cur_price,datetime.date.today())

		unsorted_list=[]
		for stock_list in stocks.rstrip().split("\n"):
			if stock_list[0]=="#":
				print stock_list
				continue
			stock_items = stock_list.split("\t");
			id 	= stock_items[0]
			price 	= float(stock_items[1])
			quantity= float(stock_items[2])
			self.get_stockinfo(id.split(".")[0])
			(StkName,CurPrice) =self.get_stockinfo(id.split(".")[0])
			cur_price=float(CurPrice)
			#cur_price=float(get_stockinfo(id.split(".")[0]))

			profit= (cur_price-price)*quantity
			profit_total=profit_total +profit
			pa=((cur_price-price)/price)*100
			cost_total= cost_total + (price*quantity)
			sale_total= sale_total + (cur_price*quantity)
	
			#print "%s \t%.2f\t%.2f\t%5.0f(%2.2f%%)"%(id, cur_price, price, profit,pa)
			sys.stdout.write('.')
			sys.stdout.flush()
			unsorted_list.append((id, StkName.strip(), cur_price, price, profit,pa))
		print ' '

		if self.nosort:
			sorted_list=unsorted_list
		else:
			sorted_list=sorted(unsorted_list, key=operator.itemgetter(-1))

		for stock in sorted_list:
			if self.cname:
			    print "%s(%s)\t \t%.2f\t%.2f\t%5.0f(%2.2f%%)"%stock
			else:
			    print "%s \t%.2f\t%.2f\t%5.0f(%2.2f%%)" \
				    %(stock[0],stock[2],stock[3],stock[4],stock[5])
		if profit_total < 0: 
			print "%.0f %0.f %0.f (%.2f%%)"%(cost_total, profit_total, \
				sale_total,(profit_total/cost_total*100))
		else:
			print "%.0f %s%0.f %0.f (%.2f%%)"%(cost_total,"+",profit_total, \
				sale_total,(profit_total/cost_total*100))


	def profile(self):
		if os.access(os.environ['HOME']+"/"+self.PROFILE,os.R_OK):
		    return 1
    		else:
		    fd = open(os.environ['HOME']+"/"+self.PROFILE,'w')
		    fd.write('#Uncomment fields before use and type in correct credentials.\n2382.TW\t50\t1000')
		    fd.close()
		    print 'Please modify '+os.environ['HOME']+"/"+self.PROFILE+' config.'
		    return 0

	def set_profile(self):
		self.PROFILE=self.SELF_PROFILE

